import 'package:base_flutter/base_flutter.dart' as b;
import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/material.dart';
import 'package:flutter_cupertino_date_picker_fork/flutter_cupertino_date_picker_fork.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:ls_work/a_elder/models/waiting_list_entity.dart';
import 'package:ls_work/a_elder/models/waiting_right_entity.dart';
import 'package:ls_work/a_yyt/models/pending_entity.dart';
import 'package:ls_work/a_yyt/models/staff_group_entity.dart';
import 'package:ls_work/a_yyt/models/take_medican_entity.dart';
import 'package:ls_work/a_yyt/page/home_pending_batch_execution_page.dart';
import 'package:ls_work/a_yyt/page/home_pending_service_batch_execution_page.dart';
import 'package:ls_work/a_yyt/page/pending_bizType_1002.dart';
import 'package:ls_work/a_yyt/page/pending_bizType_1005.dart';
import 'package:ls_work/a_yyt/page/pending_bizType_1052.dart';
import 'package:ls_work/a_yyt/page/pending_bizType_2010.dart';
import 'package:ls_work/a_yyt/page/pending_bizType_1082.dart';
import 'package:ls_work/mvp/svp_progress.dart';
import 'package:ls_work/net/HttpUtil.dart';
import 'package:ls_work/net/net.dart';
import 'package:ls_work/net/post_request.dart';
import 'package:ls_work/provider/base_list_provider.dart';
import 'package:ls_work/res/colors.dart';
import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:ls_work/res/gaps.dart';
import 'package:ls_work/res/styles.dart';
import 'package:ls_work/util/app_navigator.dart';
import 'package:ls_work/util/toast.dart';
import 'package:ls_work/widgets/click_item.dart';
import 'package:ls_work/widgets/load_image.dart';

import '../../util/flat_button.dart';
// import 'package:ls_work/widgets/my_refresh_divider_list.dart';
// import 'package:provider/provider.dart';



class HomePendingPage extends StatefulWidget {
  final int? customerId;
  HomePendingPage({Key? key, this.customerId});
  @override
  HomePendingPageState createState() => HomePendingPageState();
}

class HomePendingPageState extends State<HomePendingPage>
    with AutomaticKeepAliveClientMixin {
  BaseListProvider<WaitingRighInfo> provider =
      BaseListProvider<WaitingRighInfo>();

  @override
  bool get wantKeepAlive => true;

  LeftValue? leftItemInfo;
  List<LeftValue> leftDataList = [];
  List<LeftValue> leftgrouperDataList = [];
  List<WaitingRighInfo> rightDataList = [];
  List<WaitingRighInfo> rightGrouperDataList = [];
  List<WaitingRighInfo> rightCurrentList = [];

  List<TextEditingController> textEditingControllers = [];
  List<StaffGroupInfo> staffGroupList = [];
  List<StaffGroupInfo> staffList = [];
  List<TakeMedicanInfo> modicanList = [];

  TextEditingController textViewController = TextEditingController();
  EasyRefreshController _controller = EasyRefreshController();
  Map<String, List<WaitingRighInfo>> serviceMap = {}; //服务计划批量执行

  bool _isGrouper = false; //是否是设施长  默认否
  int _customerId = 0;
  int _bizFunction = 0;
  int _page = 1;
  int _bizId = 0;
  DateTime _selectedDate = DateTime.now();
  String _selectedTime = '';
  String _delayStaff = '';
  String _todoTime =
      DateUtil.formatDate(DateTime.now(), format: DateFormats.y_mo_d);
  // String _staffName = '';
  // int changeExecutorId;
  int _serviceTypeId = 0;
  int? _humanId;
  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      _fectData();
      _fectserviceGroupData();
      _fectGroupServiceData();
    });
    super.initState();
  }

  @override
  void dispose() {
    print('我结束了啊  ' * 5);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      appBar: AppBar(
        title: Text('待办'),
        elevation: 0.5,
        actions: <Widget>[
          GestureDetector(
            onTap: () {
              setState(() {
                _isGrouper = !_isGrouper;
                rightCurrentList =
                    _isGrouper ? rightGrouperDataList : rightDataList;
                if (_isGrouper) {
                  // print(rightCurrentList.first.bizParams.serviceItem);
                }
              });
            },
            child: Row(
              mainAxisAlignment: MainAxisAlignment.start,
              children: <Widget>[
                Text(
                  "切换",
                  style: TextStyles.textDark18,
                ),
                SizedBox(
                  width: 5,
                ),
                LoadAssetImage('home/home_change'),
                SizedBox(
                  width: 15,
                ),
              ],
            ),
          ),
        ],
      ),
      body: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Container(
            width: ScreenUtil.getScreenW(context) * 0.3,
            child: ListView.separated(
              itemCount:
                  _isGrouper ? leftgrouperDataList.length : leftDataList.length,
              itemBuilder: (_, int index) {
                return GestureDetector(
                  onTap: () {
                    if (_isGrouper) {
                      if (leftgrouperDataList[index].bizFunction ==
                          _bizFunction) {
                        return;
                      }
                      for (int i = 0; i < leftgrouperDataList.length; i++) {
                        if (i == index) {
                          leftgrouperDataList[i].isSelected = true;
                        } else {
                          leftgrouperDataList[i].isSelected = false;
                        }
                      }
                      setState(() {
                        _page = 1;
                        _bizFunction = leftgrouperDataList[index].bizFunction??0;
                      });
                      rightGrouperDataList = [];
                      _onRefresh();
                    } else {
                      if (leftDataList[index].customerId == _customerId) {
                        return;
                      }
                      leftItemInfo = leftDataList[index];
                      for (int i = 0; i < leftDataList.length; i++) {
                        if (i == index) {
                          leftDataList[i].isSelected = true;
                        } else {
                          leftDataList[i].isSelected = false;
                        }
                      }
                      setState(() {
                        _page = 1;
                        _customerId = leftDataList[index].customerId??0;
                      });
                      _onRefresh();
                    }
                  },
                  child: Container(
                    color: (_isGrouper
                            ? (leftgrouperDataList[index].isSelected??false)
                            : (leftDataList[index].isSelected??false))
                        ? Colours.bg_color
                        : Colors.white,
                    alignment: Alignment.center,
                    height: 60,
                    child: Text(
                      _isGrouper
                          ? leftgrouperDataList[index].functionName??""
                          : leftDataList[index].elderName??"",
                      textAlign: TextAlign.center,
                      style: TextStyle(
                        color: (_isGrouper
                                ? (leftgrouperDataList[index].isSelected??false)
                                : (leftDataList[index].isSelected??false))
                            ? Colors.black
                            : Colours.text_gray,
                        fontSize: 16,
                      ),
                    ),
                  ),
                );
              },
              separatorBuilder: (_, int index) {
                return Container(
                  width: double.infinity,
                  height: 1,
                  color: Colours.bg_color,
                );
              },
            ),
          ),
          Container(
            width: 1,
            color: Colours.line,
            height: ScreenUtil.getScreenH(context),
          ),
          Container(
            width: ScreenUtil.getScreenW(context) * 0.7 - 1,
            height: ScreenUtil.getScreenH(context),
            color: Colors.white,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Gaps.hGap16,
                if (_isGrouper && _bizFunction != 804) SizedBox() else Container(
                        padding: EdgeInsets.fromLTRB(12, 8, 12, 8),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.start,
                          children: [
                            FlatsButton(
                              padding: EdgeInsets.all(15),
                              color: Colors.blue,
                              highlightColor: Colors.blue[700]!,
                              child: Text(
                                _todoTime,
                                style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 16,
                                ),
                              ),
                              shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(8.0)),
                              onPressed: () {
                                _showDateTimePicker(
                                  timeType: 1,
                                  calBack: _onRefresh,
                                );
                              },
                            ),
                            Gaps.hGap16,
                            FlatsButton(
                              padding: EdgeInsets.all(15),
                              color: Colors.blue,
                              highlightColor: Colors.blue[700]!,
                              child: Text(
                                "批量执行",
                                style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 16,
                                ),
                              ),
                              shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(8.0)),
                              onPressed: () {
                                if (rightDataList.length <= 0) {
                                  return;
                                }
                                if (_isGrouper && _bizFunction == 804) {
                                  AppNavigator.push(
                                    context,
                                    HomePendingServiceBatchExecutionpage(
                                      map: serviceMap,
                                      callBack: _onRefresh,
                                    ),
                                  );
                                } else if (leftItemInfo != null) {
                                  AppNavigator.push(
                                    context,
                                    HomePendingbatchExecutionPage(
                                      elderInfo: leftItemInfo,
                                      rightDataList: rightDataList,
                                      callBack: _onRefresh,
                                    ),
                                  );
                                }
                              },
                            ),
                          ],
                        ),
                      ),
                Expanded(
                  child: EasyRefresh(
                    enableControlFinishLoad: true,
                    onRefresh: _onRefresh,
                    onLoad: _loadMore,
                    controller: _controller,
                    emptyWidget: rightCurrentList.length > 0
                        ? null
                        : Container(
                            child: Center(
                              child: Text(
                                '暂无数据',
                                style: TextStyles.textGray14,
                              ),
                            ),
                          ),
                    child: ListView.separated(
                      itemCount: rightCurrentList.length,
                      itemBuilder: (_, index) {
                        return _rightCell(rightCurrentList[index]);
                      },
                      separatorBuilder: (_, int index) {
                        return Container(
                          color: Colours.line,
                          height: 1.0,
                        );
                      },
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  ///左侧数据
  _fectData() {
    SVProgressHUD page = SVProgressHUD(context);
    page.showProgress();
    HttpUtil.instance.getDio().post(HttpApi.myGroupList).then((r) {
      page.closeProgress();
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());
        if (map["code"].toString() == "0") {
          if (map['data'] != null) {
            WaitingListEntity model = WaitingListEntity.fromJson(map);
            if ((model.data??[]).length > 0) {
              setState(() {
                model.data!.first.isSelected = true;
                leftDataList = model.data??[];
                leftItemInfo = model.data!.first;
                _customerId = model.data!.first.customerId??0;
                _page = 1;
                _onRefresh();
              });
            }
          } else {
            Toast.show(map["msg"]);
          }
        } else {
          Toast.show(map["msg"]);
        }
      } else {
        Toast.show(r.statusCode.toString());
      }
    }).catchError((e) {
      page.closeProgress();
      print(e.toString());
      Toast.show(getErrorMessage(e));
    });
  }

  ///服务小组列表
  _fectserviceGroupData() {
    SVProgressHUD page = SVProgressHUD(context);
    page.showProgress();
    HttpUtil.instance.getDio().post(HttpApi.getAllByCurBranch).then((r) {
      page.closeProgress();
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());
        if (map["code"].toString() == "0") {
          if (map['data'] != null) {
            StaffGroupEntity model = StaffGroupEntity.fromJson(map);
            if ((model.data??[]).length > 0) {
              setState(() {
                model.data!.first.isSelected = true;
                staffGroupList = model.data??[];
                _serviceTypeId = model.data!.first.serviceTypeId??0;
                _fectserviceStaffData(null);
              });
            }
          } else {
            Toast.show(map["msg"]);
          }
        } else {
          Toast.show(map["msg"]);
        }
      } else {
        Toast.show(r.statusCode.toString());
      }
    }).catchError((e) {
      page.closeProgress();
      print(e.toString());
      Toast.show(getErrorMessage(e));
    });
  }

  ///设施长 服务项目列表
  _fectGroupServiceData() {
    SVProgressHUD page = SVProgressHUD(context);
    page.showProgress();
    HttpUtil.instance.getDio().post(HttpApi.appGroupList).then((r) {
      page.closeProgress();
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());
        if (map["code"].toString() == "0") {
          if (map['data'] != null) {
            WaitingListEntity model = WaitingListEntity.fromJson(map);
            if ((model.data??[]).length > 0) {
              setState(() {
                model.data!.first.isSelected = true;
                leftgrouperDataList = model.data??[];
                _bizFunction = model.data!.first.bizFunction??0;
                fectData(_bizFunction, 1, true);
              });
            }
          } else {
            Toast.show(map["msg"]);
          }
        } else {
          Toast.show(map["msg"]);
        }
      } else {
        Toast.show(r.statusCode.toString());
      }
    }).catchError((e) {
      page.closeProgress();
      print(e.toString());
      Toast.show(getErrorMessage(e));
    });
  }

  ///服务小组组员列表
  _fectserviceStaffData(void Function(void Function())? setDialogState) {
    SVProgressHUD page = SVProgressHUD(context);
    page.showProgress();
    var map = {'serviceGroupId': _serviceTypeId};
    HttpUtil.instance
        .getDio()
        .post(HttpApi.listByGroupId, data: map,options: PostRequest.urlencodedHeader)
        .then((r) {
      page.closeProgress();
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());
        //
        if (map["code"].toString() == "0") {
          if (map['data'] != null) {
            StaffGroupEntity model = StaffGroupEntity.fromJson(map);
            if ((model.data??[]).length > 0) {
              if (setDialogState != null) {
                setDialogState(() {
                  staffList = model.data??[];
                });
              } else {
                staffList = model.data??[];
              }
            }
          } else {
            Toast.show(map["msg"]);
          }
        } else {
          Toast.show(map["msg"]);
        }
      } else {
        Toast.show(r.statusCode.toString());
      }
    }).catchError((e) {
      page.closeProgress();
      print(e.toString());
      Toast.show(getErrorMessage(e));
    });
  }

  Widget _rightCell(WaitingRighInfo info) {
    return Container(
      padding: EdgeInsets.all(12),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Text(
              _isGrouper
                  ? '${info.elderName}    ${info.roomNo ?? ''}'
                  : info.bizParams?.serviceItem ?? '',
              style: TextStyles.textDark16),
          InkWell(
            onTap: () {
              _serviceExecuteEvent(info);
            },
            child: Container(
              decoration: BoxDecoration(
                color: Colours.app_main,
                borderRadius: BorderRadius.circular(5),
              ),
              padding: EdgeInsets.fromLTRB(18, 10, 18, 10),
              child: Text(
                '执行',
                style: TextStyle(color: Colors.white),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Future _onRefresh() async {
    _page = 1;
    await fectData(_isGrouper ? _bizFunction : _customerId, _page, _isGrouper);
  }

  Future _loadMore() async {
    _page++;
    await fectData(_isGrouper ? _bizFunction : _customerId, _page, _isGrouper);
  }

  _serviceExecuteEvent(WaitingRighInfo info) {
    _selectedTime = "";
    textViewController.text = "";
    if (info.bizType == 1057) {
      ///服务计划=1057
      SVProgressHUD page = SVProgressHUD(context);
      page.showProgress();
      var map = {'id': info.bizId};
      HttpUtil.instance
          .getDio()
          .post(HttpApi.servicePlanRecordDetail, data: map,options: PostRequest.urlencodedHeader)
          .then((r) {
        page.closeProgress();
        if (r.statusCode == 200) {
          Map<String, dynamic> map = json.decode(r.toString());
          if (map["code"].toString() == "0") {
            if (map['data'] != null) {
              PendingModel model = PendingModel.fromJson(map['data']);
              textEditingControllers = [];
              _selectedDate = DateTime.now();
              _selectedTime =
                  ''; //DateUtil.formatDate(_selectedDate, format: DateFormats.full);
              textViewController.text = '';
              _bizId = info.bizId??0;
              if (model.resultMode == 0) {
                ///直接执行，不弹窗
                // _updateServicePlanRecord(isResultMode: true);
                _bottomServiceDoneSheetAlert(model);
                // Toast.show("我是直接执行");
                return;
              }
              _bottomServiceSheetAlert(model);
            } else {
              Toast.show(map["msg"]);
            }
          } else {
            Toast.show(map["msg"]);
          }
        } else {
          Toast.show(r.statusCode.toString());
        }
      }).catchError((e) {
        page.closeProgress();
        print(e.toString());
        Toast.show(getErrorMessage(e));
      });
    } else if (info.bizType == 1059) {
      ///服药=1059
      SVProgressHUD page = SVProgressHUD(context);
      page.showProgress();
      var map = {
        'sheetId': info.bizParams?.sheetId,
        'type': 3,
        'status': 0,
        'customerId': info.customerId,
      };

      HttpUtil.instance
          .getDio()
          .post(HttpApi.takeMedicineDetail, data: map,options: PostRequest.urlencodedHeader)
          .then((r) {
        // ///
        page.closeProgress();
        if (r.statusCode == 200) {
          Map<String, dynamic> map = json.decode(r.toString());
          if (map["code"].toString() == "0") {
            if (map['data'] != null) {
              TakeMedicanEntity model = TakeMedicanEntity.fromJson(map['data']);
              if ((model.rows??[]).length <= 0) {
                Toast.show('没有待服药计划');
                return;
              }
              modicanList = model.rows??[];
              for (var item in (model.rows??<TakeMedicanInfo>[])) {
                item.isSelected = true;
              }
              _bottomTakeMedicanSheetAlert(modicanList, info);
            } else {
              Toast.show(map["msg"]);
            }
          } else {
            Toast.show(map["msg"]);
          }
        } else {
          Toast.show(r.statusCode.toString());
        }
      }).catchError((e) {
        page.closeProgress();
        print(e.toString());
        Toast.show(getErrorMessage(e));
      });
    } else if (info.bizType == 1002 || info.bizType == 1003) {
      ///评估分配
      AppNavigator.push(
        context,
        PendingBizType1002(
          info: info,
          callBack: _onRefresh,
        ),
      );
    } else if (info.bizType == 1005) {
      ///评估审核
      AppNavigator.push(
        context,
        PendingBizType1005(
          info: info,
          callBack: _onRefresh,
        ),
      );
    } else if (info.bizType == 2010) {
      ///整合性计划分配
      AppNavigator.push(
        context,
        PendingBizType2010(
          info: info,
          callBack: _onRefresh,
        ),
      );
    } else if (info.bizType == 1052) {
      ///个案审核
      AppNavigator.push(
        context,
        PendingBizType1052(
          info: info,
          callBack: _onRefresh,
        ),
      );
    } else if (info.bizType == 1082) {
      ///体检报告审核
      AppNavigator.push(
        context,
        PendingBizType1082(
          info: info,
          callBack: _onRefresh,
        ),
      );
    } else {
      Toast.show('此模块暂不支持执行');
    }
  }

  ///服务执行页
  _bottomServiceSheetAlert(PendingModel model) {
    var textFields = <Widget>[];
    if ((model.result??[]).length > 0) {
      (model.result??[]).forEach((element) {
        var textEditingController = new TextEditingController();
        textEditingControllers.add(textEditingController);
        return textFields
            .add(_serviceItem(model, element, textEditingController));
      });
    }
    showModalBottomSheet(
      backgroundColor: Colors.white,
      context: context,
      isScrollControlled: true,
      isDismissible: false,
      builder: (BuildContext context) {
        return StatefulBuilder(
          builder: (context, setDialogState) {
            return Stack(
              children: <Widget>[
                SingleChildScrollView(
                  child: Container(
                    width: double.infinity,
                    padding: EdgeInsets.only(
                        bottom: MediaQuery.of(context).viewInsets.bottom), //
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      mainAxisAlignment: MainAxisAlignment.start,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: <Widget>[
                        Gaps.vGap50,
                        Text(
                          '${model.expenseItem}',
                          style:
                              TextStyle(fontSize: 20, color: Colours.text_dark),
                        ),
                        Gaps.vGap15,
                        Text(
                          '${model.elderName}   ${model.bedNo}',
                          style: TextStyles.textGray18,
                        ),
                        Gaps.vGap50,
                        ClickItem(
                          title: "执行时间：",
                          content: _selectedTime,
                          onTap: () {
                            _showDateTimePicker(calBack: () {
                              setDialogState(() {
                                _selectedTime = _selectedTime;
                              });
                            });
                          },
                        ),
                        (model.result??[]).length > 0
                            ? Column(
                                children: textFields,
                              )
                            : Gaps.empty,
                        Container(
                          padding: EdgeInsets.all(20),
                          color: Colors.white,
                          alignment: Alignment.topLeft,
                          height: 100,
                          child: TextField(
                            controller: textViewController,
                            maxLines: 5,
                            // maxLength: 300,
                            autofocus: false,
                            decoration: InputDecoration(
                              hintText: "请输入备注内容",
                              hintMaxLines: 20,
                              fillColor: Colours.bg_color,
                              filled: true,
                              border: InputBorder.none,
                            ),
                          ),
                        ),
                        Gaps.vGap16,
                        Container(
                          width: double.infinity,
                          height: 50,
                          padding: EdgeInsets.fromLTRB(12, 0, 12, 0),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                            children: <Widget>[
                              FlatsButton(
                                color: Colours.text_gray,
                                onPressed: () {
                                  Navigator.pop(context);
                                },
                                child: Text(
                                  '取消',
                                  style: TextStyle(color: Colors.white),
                                ),
                              ),
                              FlatsButton(
                                color: Colours.app_main,
                                onPressed: () {
                                  _updateServicePlanRecord(model: model);
                                },
                                child: Text(
                                  '确定',
                                  style: TextStyle(color: Colors.white),
                                ),
                              ),
                            ],
                          ),
                        ),
                        Gaps.vGap50,
                      ],
                    ),
                  ),
                ),
                Positioned(
                  left: 20,
                  top: 20,
                  child: FlatsButton(
                    color: Colors.blue[300]!,
                    onPressed: () {
                      Navigator.pop(context);
                      _bottomDelayServiceSheetAlert(model: model);
                    },
                    child: Text(
                      '延迟执行',
                      style: TextStyle(color: Colors.white),
                    ),
                  ),
                ),
              ],
            );
          },
        );
      },
    );
  }

  ///服务执行页 - 直接完成过渡界面
  _bottomServiceDoneSheetAlert(PendingModel model) {
    showModalBottomSheet(
      backgroundColor: Colors.white,
      context: context,
      isScrollControlled: true,
      isDismissible: false,
      builder: (BuildContext context) {
        return StatefulBuilder(
          builder: (context, setDialogState) {
            return Stack(
              children: <Widget>[
                SingleChildScrollView(
                  child: Container(
                    width: double.infinity,
                    padding: EdgeInsets.only(
                        bottom: MediaQuery.of(context).viewInsets.bottom), //
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      mainAxisAlignment: MainAxisAlignment.start,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: <Widget>[
                        Gaps.vGap50,
                        Text(
                          '${model.expenseItem}',
                          style:
                              TextStyle(fontSize: 20, color: Colours.text_dark),
                        ),
                        Gaps.vGap15,
                        Text(
                          '${model.elderName}   ${model.bedNo}',
                          style: TextStyles.textGray18,
                        ),
                        Gaps.vGap50,
                        ClickItem(
                          title: "执行时间：",
                          content: _selectedTime,
                          onTap: () {
                            _showDateTimePicker(calBack: () {
                              setDialogState(() {
                                _selectedTime = _selectedTime;
                              });
                            });
                          },
                        ),
                        Gaps.vGap15,
                        Container(
                          padding: EdgeInsets.all(20),
                          color: Colors.white,
                          alignment: Alignment.topLeft,
                          height: 100,
                          child: TextField(
                            controller: textViewController,
                            maxLines: 5,
                            // maxLength: 300,
                            autofocus: false,
                            decoration: InputDecoration(
                              hintText: "请输入备注内容",
                              hintMaxLines: 20,
                              fillColor: Colours.bg_color,
                              filled: true,
                              border: InputBorder.none,
                            ),
                          ),
                        ),
                        Gaps.vGap50,
                        Container(
                          width: double.infinity,
                          height: 50,
                          padding: EdgeInsets.fromLTRB(12, 0, 12, 0),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                            children: <Widget>[
                              FlatsButton(
                                color: Colours.text_gray,
                                onPressed: () {
                                  Navigator.pop(context);
                                },
                                child: Text(
                                  '取消',
                                  style: TextStyle(color: Colors.white),
                                ),
                              ),
                              FlatsButton(
                                color: Colours.app_main,
                                onPressed: () {
                                  // _updateServicePlanRecord(model: model);
                                  _updateServicePlanRecord(isResultMode: true);
                                },
                                child: Text(
                                  '确定',
                                  style: TextStyle(color: Colors.white),
                                ),
                              ),
                            ],
                          ),
                        ),
                        Gaps.vGap50,
                      ],
                    ),
                  ),
                ),
                Positioned(
                  left: 20,
                  top: 20,
                  child: FlatsButton(
                    color: Colors.blue[300]!,
                    onPressed: () {
                      Navigator.pop(context);
                      _bottomDelayServiceSheetAlert(
                          model: model, isDoneItem: true);
                    },
                    child: Text(
                      '延迟执行',
                      style: TextStyle(color: Colors.white),
                    ),
                  ),
                ),
              ],
            );
          },
        );
      },
    );
  }

  ///服务延迟执行页
  _bottomDelayServiceSheetAlert(
      {Key? key, required PendingModel model, bool isDoneItem = false}) {
    showModalBottomSheet(
      backgroundColor: Colors.white,
      context: context,
      isScrollControlled: true,
      isDismissible: false,
      builder: (BuildContext context) {
        return StatefulBuilder(builder: (context, setDialogState) {
          return Stack(
            children: <Widget>[
              SingleChildScrollView(
                child: Container(
                  width: double.infinity,
                  padding: EdgeInsets.only(
                      bottom: MediaQuery.of(context).viewInsets.bottom), //
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      Gaps.vGap50,
                      Text(
                        '${model?.expenseItem??""}',
                        style:
                            TextStyle(fontSize: 20, color: Colours.text_dark),
                      ),
                      Gaps.vGap15,
                      Text(
                        '${model?.elderName??""}   ${model?.bedNo??""}',
                        style: TextStyles.textGray18,
                      ),
                      Gaps.vGap50,
                      _serviceDelayItem(
                        '   延迟时间',
                        '$_selectedTime',
                        () {
                          _showDateTimePicker(calBack: () {
                            setDialogState(() {
                              _selectedTime = _selectedTime;
                            });
                          });
                        },
                      ),
                      _serviceDelayItem(
                        '更换执行人',
                        _delayStaff,
                        () {
                          _bottomDelayChangeManagerSheetAlert(() {
                            setDialogState(() {
                              _delayStaff = _delayStaff;
                            });
                          });
                        },
                      ),
                      Gaps.vGap15,
                      Container(
                        padding: EdgeInsets.all(20),
                        color: Colors.white,
                        alignment: Alignment.topLeft,
                        height: 200,
                        child: TextField(
                          controller: textViewController,
                          maxLines: 10,
                          maxLength: 300,
                          autofocus: false,
                          decoration: InputDecoration(
                            hintText: "请输入备注内容",
                            hintMaxLines: 20,
                            fillColor: Colours.bg_color,
                            filled: true,
                            border: InputBorder.none,
                          ),
                        ),
                      ),
                      Gaps.vGap50,
                      Container(
                        width: double.infinity,
                        height: 50,
                        padding: EdgeInsets.fromLTRB(12, 0, 12, 0),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                          children: <Widget>[
                            FlatsButton(
                              color: Colours.text_gray,
                              onPressed: () {
                                Navigator.pop(context);
                              },
                              child: Text(
                                '取消',
                                style: TextStyle(color: Colors.white),
                              ),
                            ),
                            FlatsButton(
                              color: Colours.app_main,
                              onPressed: () {
                                _updateServicePlanRecord(
                                    model: model, isDelayService: true);
                              },
                              child: Text(
                                '确定',
                                style: TextStyle(color: Colors.white),
                              ),
                            ),
                          ],
                        ),
                      ),
                      Gaps.vGap50,
                    ],
                  ),
                ),
              ),
              Positioned(
                left: 20,
                top: 20,
                child: FlatsButton(
                  color: Colors.blue[300]!,
                  onPressed: () {
                    Navigator.pop(context);
                    if (isDoneItem) {
                      _bottomServiceDoneSheetAlert(model);
                    } else {
                      _bottomServiceSheetAlert(model);
                    }
                  },
                  child: Text(
                    '恢复执行',
                    style: TextStyle(color: Colors.white),
                  ),
                ),
              ),
            ],
          );
        });
      },
    );
  }

  ///更换执行人
  _bottomDelayChangeManagerSheetAlert(VoidCallback callback) {
    showModalBottomSheet(
      backgroundColor: Colors.white,
      context: context,
      isScrollControlled: true,
      isDismissible: false,
      builder: (BuildContext context) {
        return StatefulBuilder(builder: (context, setDialogState) {
          return Stack(
            children: <Widget>[
              Container(
                height: ScreenUtil.getScreenH(context) * 2 / 3,
                padding: EdgeInsets.only(top: 90),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Container(
                      width: ScreenUtil.getScreenW(context) * 0.3,
                      color: Colors.white,
                      child: ListView.separated(
                        itemCount: staffGroupList.length,
                        itemBuilder: (_, int index) {
                          return GestureDetector(
                            onTap: () {
                              if (staffGroupList[index].serviceTypeId ==
                                  _serviceTypeId) {
                                return;
                              }
                              for (int i = 0; i < staffGroupList.length; i++) {
                                if (i == index) {
                                  staffGroupList[i].isSelected = true;
                                } else {
                                  staffGroupList[i].isSelected = false;
                                }
                              }
                              setDialogState(() {
                                _serviceTypeId =
                                    staffGroupList[index].serviceTypeId??0;
                                staffList = [];
                                _fectserviceStaffData(setDialogState);
                              });
                            },
                            child: Container(
                              color: staffGroupList[index].isSelected
                                  ? Colours.bg_color
                                  : Colors.white,
                              alignment: Alignment.center,
                              height: 60,
                              child: Text(
                                staffGroupList[index].name??"",
                                style: TextStyle(
                                  color: Colors.black,
                                  fontSize: 16,
                                ),
                              ),
                            ),
                          );
                        },
                        separatorBuilder: (context, int) {
                          return Container(
                            width: double.infinity,
                            color: Colours.line,
                            height: 1,
                          );
                        },
                      ),
                    ),
                    Container(
                      width: 1,
                      color: Colours.line,
                      height: ScreenUtil.getScreenH(context),
                    ),
                    Container(
                      width: ScreenUtil.getScreenW(context) * 0.7 - 1,
                      color: Colours.bg_color,
                      child: ListView.separated(
                        itemCount: staffList.length,
                        itemBuilder: (_, int index) {
                          return GestureDetector(
                            onTap: () {
                              setDialogState(() {
                                _delayStaff = staffList[index].userName??"";
                                _humanId = staffList[index].humanId;
                              });
                            },
                            behavior: HitTestBehavior.opaque,
                            child: Container(
                              padding: EdgeInsets.all(15),
                              color: Colors.white,
                              child: Text(
                                '${staffList[index].userName}',
                                textAlign: TextAlign.center,
                              ),
                            ),
                          );
                        },
                        separatorBuilder: (context, int) {
                          return Container(
                            width: ScreenUtil.getScreenW(context),
                            color: Colours.line,
                            height: 1,
                          );
                        },
                      ),
                    )
                  ],
                ),
              ),
              Positioned(
                left: 20,
                top: 20,
                child: FlatsButton(
                  color: Colours.text_gray,
                  onPressed: () {
                    Navigator.pop(context);
                  },
                  child: Text(
                    '取消',
                    style: TextStyle(color: Colours.text_dark),
                  ),
                ),
              ),
              Positioned(
                right: 20,
                top: 20,
                child: FlatsButton(
                  color: Colors.blue[300]!,
                  onPressed: () {
                    callback();
                    Navigator.pop(context);
                  },
                  child: Text(
                    '确定',
                    style: TextStyle(color: Colors.white),
                  ),
                ),
              ),
              Positioned(
                right: 0,
                left: 0,
                top: 90,
                child: Gaps.line,
              ),
              Positioned(
                right: 200.0,
                left: 200.0,
                top: 35,
                child: Text(
                  '$_delayStaff',
                  textAlign: TextAlign.center,
                  style: TextStyles.textDark18,
                ),
              ),
            ],
          );
        });
      },
    );
  }

  ///服药
  _bottomTakeMedicanSheetAlert(
      List<TakeMedicanInfo> modicanList, WaitingRighInfo info) {
    showModalBottomSheet(
      backgroundColor: Colors.white,
      context: context,
      isScrollControlled: true,
      isDismissible: false,
      builder: (BuildContext context) {
        return StatefulBuilder(
          builder: (context, setDialogState) {
            return Container(
              height: ScreenUtil.getScreenH(context) * 2 / 3,
              color: Colors.white,
              child: Column(
                children: <Widget>[
                  Gaps.vGap50,
                  Text(
                    '${info.bizParams?.serviceItem??""}',
                    style: TextStyle(fontSize: 20, color: Colours.text_dark),
                  ),
                  Gaps.vGap15,
                  Text(
                    '${info.elderName}   ${info.roomNo}',
                    style: TextStyles.textGray18,
                  ),
                  Gaps.vGap50,
                  Expanded(
                    child: ListView.separated(
                      itemBuilder: (context, index) {
                        return Container(
                          padding: EdgeInsets.all(15),
                          child: GestureDetector(
                            onTap: () {
                              if (modicanList.length == 1) {
                                return;
                              } else {
                                setDialogState(() {
                                  modicanList[index].isSelected =
                                      !modicanList[index].isSelected;
                                });
                              }
                            },
                            behavior: HitTestBehavior.opaque,
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.start,
                              children: <Widget>[
                                Text(
                                  '${modicanList[index].medicineName}',
                                  style: TextStyles.textDark18,
                                ),
                                Text(
                                  '       ${modicanList[index].takeCount}${modicanList[index].takeUnitDesc}',
                                  style: TextStyles.textNormal16,
                                ),
                                Expanded(
                                  child: Text(
                                      '       ${modicanList[index].useTypeDesc ?? ''}'),
                                ),
                                modicanList[index].isSelected
                                    ? LoadAssetImage(
                                        'selected',
                                        height: 30,
                                        width: 30,
                                      )
                                    : Gaps.empty,
                              ],
                            ),
                          ),
                        );
                      },
                      separatorBuilder: (context, index) => Gaps.line,
                      itemCount: modicanList.length,
                    ),
                  ),
                  Container(
                    padding: EdgeInsets.all(30),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceAround,
                      children: <Widget>[
                        FlatsButton(
                          color: Colours.text_gray,
                          onPressed: () {
                            Navigator.pop(context);
                          },
                          child: Text(
                            '取消',
                            style: TextStyle(color: Colours.text_dark),
                          ),
                        ),
                        FlatsButton(
                          color: Colors.blue[300]!,
                          onPressed: () {
                            _medicanOperateMothed();
                            Navigator.pop(context);
                          },
                          child: Text(
                            '确定',
                            style: TextStyle(color: Colors.white),
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            );
          },
        );
      },
    );
  }

  void _updateServicePlanRecord(
      { PendingModel? model,
      bool isResultMode = false,
      bool isDelayService = false}) {
    ///服务计划=1057
    Map map = {
      'id': _bizId,
      'executeStatus': isDelayService ? 1 : 0,
      "remark": textViewController.text ?? "",
    };
    if (isDelayService) {
      if (TextUtil.isEmpty(_selectedTime) && _humanId == null) {
        Toast.show('延迟时间和执行人不能同时为空');
        return;
      }
      if (!TextUtil.isEmpty(textViewController.text)) {
        map['remark'] = textViewController.text;
      }
      if (!TextUtil.isEmpty(_selectedTime)) {
        map['delayTime'] = _selectedTime;
      }
      if (_humanId != null) {
        map['changeExecutorId'] = _humanId;
      }
    } else {
      map['finishTime'] = _selectedTime != null ? _selectedTime : "";
      if (isResultMode == false) {
        var temp = [];
        if(model!=null){
          for (var i = 0; i < (model.result??[]).length; i++) {
            temp.add({
              'value': textEditingControllers[i].text,
              'rangeTo':
              model.result![i].rangeTo != null ? model.result![i].rangeTo : "",
              'rangeFrom': model.result![i].rangeFrom != null
                  ? model.result![i].rangeFrom
                  : "",
              'subItem': model.result![i].subItem,
            });
          }
        }
        map['result'] = jsonEncode(temp);
      }
    }

    Map map1 = new Map<String, dynamic>.from(map);
    SVProgressHUD page = SVProgressHUD(context);
    page.showProgress();
    HttpUtil.instance
        .getDio()
        .post('${HttpApi.updateServicePlanRecord}?${requestParams(map1)}')
        .then((r) {
      page.closeProgress();
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());
        //
        if (map["code"].toString() == "0") {
          Toast.show(map["msg"]);
          _onRefresh();
          Navigator.pop(context);
        } else {
          Toast.show(map["msg"]);
        }
      } else {
        Toast.show(r.statusCode.toString());
      }
    }).catchError((e) {
      page.closeProgress();
      print(e.toString());
      Toast.show(getErrorMessage(e));
    });
  }

  _medicanOperateMothed() {
    bool hasSelected = false;
    List<int> ids = [];
    for (var item in modicanList) {
      if (item.isSelected) {
        ids.add(item.id??0);
        hasSelected = true;
      }
    }
    if (hasSelected == false) {
      Toast.show('请选择至少一种服药项目');
    }
    SVProgressHUD page = SVProgressHUD(context);
    page.showProgress();
    var map = {
      'operType': 3,
      'ids': ids,
      'operDate': DateUtil.formatDate(DateTime.now(), format: DateFormats.full),
      'remark': '',
    };

    HttpUtil.instance
        .getDio()
        .post(HttpApi.takeMedicineOperate, data: map)
        .then((r) {
      // ///
      page.closeProgress();
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());
        if (map["code"].toString() == "0") {
          Toast.show(map["msg"]);
        } else {
          Toast.show(map["msg"]);
        }
      } else {
        Toast.show(r.statusCode.toString());
      }
    }).catchError((e) {
      page.closeProgress();
      print(e.toString());
      Toast.show(getErrorMessage(e));
    });
  }

  Widget _serviceItem(
      PendingModel model, PendingInfo e, TextEditingController controller) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Container(
          padding: EdgeInsets.fromLTRB(0, 0, 12, 0),
          margin: EdgeInsets.only(left: 15),
          width: ScreenUtil.getScreenW(context),
          decoration: BoxDecoration(
            border: Border(
              bottom: Divider.createBorderSide(context,
                  color: Colours.line, width: 1),
            ),
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              Text(
                '${e.subItem}',
                style: TextStyles.textDark18,
              ),
              SizedBox(
                width: 10,
              ),
              Expanded(
                child: TextField(
                  keyboardType: TextInputType.number,
                  textAlign: TextAlign.center,
                  style: TextStyles.textGray18,
                  controller: controller,
                  autofocus: false,
                  decoration: InputDecoration(
                    hintText: "输入${e.subItem}数值",
                    hintStyle: TextStyles.textGray18,
                    fillColor: Colors.white,
                    filled: true,
                    border: InputBorder.none,
                  ),
                ),
              ),
              Text(
                '${model.resultUnit ?? ''}',
                style: TextStyles.textDark18,
              )
            ],
          ),
        ),
        Gaps.vGap15,
        Container(
          padding: EdgeInsets.fromLTRB(15, 0, 15, 15),
          child: Text(
            '正常范围：${e.rangeFrom != "null" ? e.rangeFrom : ""} ~ ${e.rangeTo != "null" ? e.rangeTo : ""}',
            style: TextStyles.textGray14,
          ),
        ),
        Gaps.vGap16,
      ],
    );
  }

  Widget _serviceDelayItem(String title, String content, Function() onTap) {
    return GestureDetector(
      onTap: onTap,
      behavior: HitTestBehavior.opaque,
      child: Container(
        padding: EdgeInsets.fromLTRB(0, 15, 15, 15),
        margin: EdgeInsets.only(left: 15),
        width: ScreenUtil.getScreenW(context),
        decoration: BoxDecoration(
          border: Border(
            bottom: Divider.createBorderSide(context,
                color: Colours.line, width: 1),
          ),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
            Text(
              '$title',
              style: TextStyles.textDark18,
            ),
            SizedBox(
              width: 10,
            ),
            Expanded(
              child: Text(
                '$content',
                textAlign: TextAlign.center,
                style: TextStyles.textDark18,
              ),
            ),
            LoadAssetImage(
              'ic_arrow_right',
              width: 25,
              height: 45,
            ),
          ],
        ),
      ),
    );
  }

  ///调起时间选择器
  void _showDateTimePicker({Key? key, int timeType = 0, VoidCallback? calBack}) {
    DatePicker.showDatePicker(
      context,
      minDateTime: DateTime.parse("1999-01-01"),
      maxDateTime: DateTime.parse("2099-01-01"),
      initialDateTime: _selectedDate,
      dateFormat: timeType == 1 ? DateFormats.y_mo_d : "yyyy-MM-dd EEE,H时:m分",
      locale: DateTimePickerLocale.zh_cn,
      pickerTheme: DateTimePickerTheme(
        showTitle: true,
        cancel: Text("取消"),
        confirm: Text('确定'),
      ),
      pickerMode: timeType == 1
          ? DateTimePickerMode.date
          : DateTimePickerMode.datetime, // show TimePicker
      onConfirm: (dateTime, List<int> index) {
        setState(() {
          if (timeType == 1) {
            _todoTime =
                DateUtil.formatDate(dateTime, format: DateFormats.y_mo_d);
            if(calBack!=null){
              calBack();
            }
            print(_todoTime);
          } else {
            _selectedDate = dateTime;
            this._selectedTime =
                DateUtil.formatDate(dateTime, format: 'yyyy-MM-dd HH:mm:ss');
            print(_selectedTime);
            if(calBack!=null){
              calBack();
            }
          }
        });
      },
    );
  }

  Future fectData(int customerId, int page, bool isGrouper) async {
    var map = {
      'page': _page,
      'rows': 50,
      'customerId': customerId,
      "queryType": 1,
      "startDateFin1": _todoTime,
      "startDateFin2": _todoTime,
    };
    if (isGrouper) {
      map = {'bizFunction': customerId};
    }

    String url = isGrouper ? HttpApi.todoGrouperReceive : HttpApi.todoReceive;
    SVProgressHUD page = SVProgressHUD(context);
    page.showProgress();
    HttpUtil.instance
        .getDio()
        .post(url, data: isGrouper ? FormData.fromMap(map) : map)
        .then((r) {
      page.closeProgress();
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());
        if (map["code"].toString() == "0") {
          if (map['data'] != null) {
            WaitingRighrEntity model = WaitingRighrEntity.fromJson(map['data']);
            if ((model.rows??[]).length > 0) {
              _controller.finishLoad(
                  success: true, noMore: (model.rows??[]).length != 50);
              if (_page == 1) {
                /// 刷新
                if (isGrouper) {
                  rightGrouperDataList.clear();
                  rightGrouperDataList.addAll(model.rows??[]);
                } else {
                  rightDataList.clear();
                  rightDataList.addAll(model.rows??[]);
                }
              } else {
                if (isGrouper) {
                  rightGrouperDataList.addAll(model.rows??[]);
                } else {
                  rightDataList.addAll(model.rows??[]);
                }
              }
            } else {
              if (_page == 1) {
                /// 没有数据
                if (isGrouper) {
                  rightGrouperDataList.clear();
                } else {
                  rightDataList.clear();
                }
              }
            }
            setState(() {
              if (isGrouper) {
                rightCurrentList = rightGrouperDataList;
                if (_bizFunction == 804) {
                  if (isGrouper && rightGrouperDataList.length > 0) {
                    serviceMap = new Map.fromIterable(
                      rightGrouperDataList,
                      key: (info) => info.bizParams.serviceItem,
                      value: (value) {
                        return rightGrouperDataList
                            .where((item) =>
                                item.bizParams?.serviceItem ==
                                value.bizParams.serviceItem)
                            .toList();
                      },
                    );
                  }
                }
              } else {
                rightCurrentList = rightDataList;
              }
              print('rightCurrentList.length - ${rightCurrentList.length}');
            });
          } else {
            Toast.show(map["msg"]);
          }
        }
      } else {
        Toast.show(r.statusCode.toString());
        // view.provider.setHasMore(false);
        // view.provider.setStateType(StateType.empty);
      }
    }).catchError((e) {
      page.closeProgress();
      print(e.toString());
      // view.provider.setHasMore(false);
      // view.provider.setStateType(StateType.empty);
      Toast.show(getErrorMessage(e));
    });
  }
}
